package cn.com.dstz.admin.action;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.FileUtils;
import cn.com.dstz.utils.FillNameQuery;
import cn.com.dstz.utils.ValidUtils;
import cn.com.dstz.web.constants.Constants;

/**
 * 软件配置的修改
 * 
 * 现已经开启了上传功能, 那么就要为上传的文件做一个资源管理
 * 所以现在需要一个资源管理器 
 * 
 * 皮肤目录迁移至根目录，
 * 在update.txt中增加皮肤设置
 * 数据库中增加皮肤表，更良好的控制皮肤
 * id,  皮肤名称,   根目录,  皮肤的logo,  创建时间
 * 提供皮肤上传功能，可以上传jpg,png,jpeg,txt,gif 文件
 * 
 * skin/logo 存放皮肤的logo
 * 
 * 
 */
public class SoftAct extends BaseAction{
	
	public String tosoft( ){
		getRequest( ).setAttribute( "sessionId", getSession( ).getId( ) );
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		
		Map< String, Object > intermediate = getIntermediate( admin );
		
		String directory = getUploadDirectory( intermediate, admin ); // 获取目录
		String realPath = getRealPath( "/" );
		
		String updateTxt = realPath + directory ;
		
		makeDirs( updateTxt );
		
		File updateTxtFile = new File( updateTxt  + "/update.txt" );
		
		if( !updateTxtFile.exists( ) ){
			FileUtils.writeFile( updateTxtFile, this.initUpdateTxt( intermediate ) );
		}else{
			List< String > setList = readToFile( updateTxtFile );
			
			getRequest( ).setAttribute("agentSet", setList );
		}
		
		return "soft";
	}
	
	public void soft( ){
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		
		Map< String, Object > intermediate = getIntermediate( admin );
		
		String directory = getUploadDirectory( intermediate, admin ); // 获取目录
		String realPath = getRealPath( "/" );
		
		String updateTxt = realPath + directory ;
		
		File updateTxtFile = new File( updateTxt  + "/update.txt" );
		
		FileReader fr = null;
		BufferedReader br = null;
		ArrayList<String> agentSet=new ArrayList<String>();
		ArrayList<String> agentSet1=new ArrayList<String>();
		try{
			fr = new FileReader(updateTxtFile);
			br = new BufferedReader(fr);
			String readString=br.readLine();
			
			while(readString!=null&&!readString.equals("")){
				agentSet.add(readString);
				readString=br.readLine();
			}
			
		}catch( Exception e ){
			e.printStackTrace();
		}finally{
			try{
				br.close();
				fr.close();
			}catch( IOException e ){
				e.printStackTrace();
			}
			
		}
		
		for (String string : agentSet) {
			if(string.indexOf("softname=")==0){
				string="softname="+ this.basic_softname;
				
			}else if(string.indexOf("logo=")==0){
				string="logo=" + getLogo( updateTxt, directory );
				
			}else if(string.indexOf("homepage=")==0){
				string="homepage="+this.basic_homepage;
			}else if(string.indexOf("top1=")==0){
				string="top1="+ this.topbutton_rightfirst;
				
			}else if(string.indexOf("top1y=")==0){
				string="top1y="+this.topbutton_rightdisplay;
				
			}else if(string.indexOf("top2=")==0){
				string="top2="+this.topbutton_rightsecond;
				
			}else if(string.indexOf("topurl2=")==0){
				string="topurl2="+ this.topbutton_rightsecond_url;
				
				
			}else if(string.indexOf("you2=")==0){
				string="you2="+ this.topbutton_rightthird_blank;
				
			}else if(string.indexOf("top3=")==0){
				string="top3="+ this.topbutton_rightthird;
				
			}else if(string.indexOf("topurl3=")==0){
				string="topurl3="+topbutton_rightthird_url;
				
			}else if(string.indexOf("you1=")==0){
				string="you1="+ this.topbutton_rightsecond_blank;
				
			}else if(string.indexOf("left1=")==0){
				string="left1="+this.leftbutton_first;
				
			}else if(string.indexOf("left2=")==0){
				string="left2="+this.leftbutton_second;
			}else if(string.indexOf("left3=")==0){
				string="left3="+this.leftbutton_third;
			}else if(string.indexOf("lefturl3=")==0){
				string="lefturl3="+ this.leftbutton_third_url;
			}else if(string.indexOf("left4=")==0){
				string="left4="+ this.leftbutton_four;
			}else if(string.indexOf("lefturl4=")==0){
				string="lefturl4="+  this.leftbutton_four_url;
			}else if(string.indexOf("left5=")==0){
				string="left5="+ this.leftbutton_five;
			}else if(string.indexOf("lefturl5=")==0){
				string="lefturl5="+ this.leftbutton_five_url;
			}else if(string.indexOf("left6=")==0){
				string="left6="+ this.leftbutton_six;
			}else if(string.indexOf("lefturl6=")==0){
				string="lefturl6="+ this.leftbutton_six_url;;
			}else if(string.indexOf("pifu=")==0){
				string="pifu=01";
			}else if(string.indexOf("aid=")==0){
				string="aid="+ intermediate.get( "id" );
			}else if(string.indexOf("topaid=")==0){
				string="topaid="+ intermediate.get( "id" );
			}
			agentSet1.add(string);
		}
		
		FileWriter fw = null;
		BufferedWriter bw = null;
		
		try{
			fw = new FileWriter(updateTxtFile);
			bw = new BufferedWriter(fw);
			for (String string2 : agentSet1) {
				bw.write(string2);
				bw.newLine();
			}
			
		}catch( IOException e ){
			e.printStackTrace();
		}finally{
			try{
				bw.close();
			}catch( IOException e ){
				e.printStackTrace();
			}
			try{
				fw.close();
			}catch( IOException e ){
				e.printStackTrace();
			}
		}
		
		Object version = intermediate.get( "version" );
		int intVersion = 1;
		if( version != null ){
			intVersion = ( Integer ) version;
		}
		
		baseService.update( "dstzagent", DataBaseUtils.getData( new String[]{
				"version"
		}, new Object[]{
				intVersion + 1
		} ), DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				intermediate.get( "id" )
		} ) );
		
		ajaxResponse( 0 );
		return;
		
		
	}
	
	private String getLogo( String directory, String notRealPath ){
		File file = new File( directory );
		String [] files = file.list( new FilenameFilter( ){
			public boolean accept( File dir, String name ) {
				return name.contains( "logo" );
			}
		});
		
		if( files != null && files.length > 0 ){
			return notRealPath + files[ 0 ];
		}
		
		return "";
		
	}
	
	public void toupload( ){
		HttpServletResponse response = ServletActionContext.getResponse( );
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );	// 
		
		initUploadResponse( response );
		
		Map< String, Object > intermediate = getIntermediate( admin );
		String directory = getUploadDirectory( intermediate, admin );
		
		String realPath = getRealPath( "/" );
		
		String format = "jpg,png,gif,jpeg";
		String [] suffixAndName = ValidUtils.validSuffixAndName ( Filename, format );
		String logoName =  directory + "logo." + suffixAndName[ 0 ];
		
		File uploadFile = new File( realPath + logoName );
		
		try{
			org.apache.commons.io.FileUtils.copyFile(Filedata, uploadFile);
		}catch( IOException e ){
			e.printStackTrace();
		}
		
		this.ajaxResponse(  getRequest( ).getContextPath( ) + logoName);
		return;
	}
	
	private List< String > readToFile( File file ){
		
		FileReader fr = null;
		BufferedReader br = null;
		List< String > agentSet = new ArrayList<String>( );
		try{
			fr = new FileReader( file );
			br = new BufferedReader(fr);
			String readString=br.readLine();
			
			int isReadHeader=0;
			while(readString!=null&&!readString.equals("")){
				if(isReadHeader==0){
					if(readString.equals("[jbpz]")){
						isReadHeader=1;
					}
					readString=br.readLine();
					continue;
				}else{
					if(readString.contains("pifu=")){
						break;
					}
					readString=readString.substring(readString.indexOf("=")+1);
					agentSet.add(readString);
					readString=br.readLine();
				}
			}
		}catch( Exception e ){
			e.printStackTrace();
		}finally{
			try{
				br.close();
				fr.close();
			}catch( IOException e ){
				e.printStackTrace();
			}
			
		}
		
		return agentSet;
	}
	
	private String initUpdateTxt( Map< String, Object > intermediate ){
		
		
		StringBuffer buffer = new StringBuffer( );
		
		appendContent("[system]", buffer );
		appendContent("run_udafters=RunDa.exe", buffer );
		appendContent("close_proc1=RunDa.exe", buffer );
		appendContent("[UI]", buffer );
		appendContent("noupdate_win=1", buffer );
		appendContent("noupdate_win_msg=目前已是最新版本，无需升级！", buffer );
		appendContent("start_win=1", buffer );
		appendContent("start_win_msg=发现新版本，是否立即更新？最新版本：5.61 beta版（更新于2013-01-17）更新内容：优化读取速度，加入统计代码。如360等防火墙提示，请点击通过。", buffer );
		appendContent("dl_win=1", buffer );
		appendContent("dl_win_msg=下载文件失败，请稍后再试！", buffer );
		appendContent("end_win1=1", buffer );
		appendContent("end_win2=1", buffer );
		appendContent("end_win1_msg=升级完成！", buffer );
		appendContent("end_win2_msg=升级失败，请到官方网站重新下载软件！", buffer );
		appendContent("close_win=1", buffer );
		appendContent("close_win_msg=本次升级将会关闭一些相关的进程，请保存好数据后继续！", buffer );
		appendContent("[file0]", buffer );
		appendContent("urls=url0=http://sp.dstz.com.cn/daili/44/update0415.zip", buffer );
		appendContent("ver=1.0.1", buffer );
		appendContent("uncompress=1", buffer );
		appendContent("modify_ver=1", buffer );
		appendContent("runme=1", buffer );
		appendContent("op_mode=0", buffer );
		appendContent("show_type=0", buffer );
		appendContent("randomsel=0", buffer );
		appendContent("tryallurl=0", buffer );
		appendContent("[jbpz]", buffer );
		appendContent("softname=", buffer );
		appendContent("logo=", buffer );
		appendContent("homepage=", buffer );
		appendContent("top1=", buffer );
		appendContent("top1y=", buffer );
		appendContent("top2=", buffer );
		appendContent("topurl2=", buffer );
		appendContent("you2=", buffer );
		appendContent("top3=", buffer );
		appendContent("topurl3=", buffer );
		appendContent("you1=", buffer );
		appendContent("left1=", buffer );
		appendContent("left2=", buffer );
		appendContent("left3=", buffer );
		appendContent("lefturl3=", buffer );
		appendContent("left4=", buffer );
		appendContent("lefturl4=http://sp.dstz.com.cn/net/fenxi.aspx?aid="+ intermediate.get( "id" ), buffer );
		appendContent("left5=", buffer );
		appendContent("lefturl5=", buffer );
		appendContent("left6=", buffer );
		appendContent("lefturl6=http://sp.dstz.com.cn/net/gonggao.aspx?aid="+ intermediate.get( "id" ), buffer );
		appendContent("pifu=01", buffer );
		appendContent("aid="+ intermediate.get( "id" ), buffer);
		appendContent("topaid="+ intermediate.get( "id" ), buffer);
		appendContent("[bcpz]", buffer );
		appendContent("mbzcx=market.dll", buffer );
		appendContent("hangqing=rundashangping", buffer );
		appendContent("hqdbwz=-47", buffer );
		appendContent("hqzbwz=-4", buffer );
		appendContent("hqgd=75", buffer );
		appendContent("hqkd=8", buffer );
		
		return buffer.toString( );
		
	}
	
	
	private void initUploadResponse( HttpServletResponse response ){
		response.setHeader("Expires", "0");
		response.setHeader("Cache-Control", "no-store, private, post-check=0, pre-check=0, max-age=0");
		response.setHeader("Pragma", "no-cache");
	}

	private Map< String, Object > getIntermediate( Map< String, Object > admin ){
		String sql = "select * from dstzagent where id=:id";
		Map< String, Object > intermediate = baseService.queryForMap( sql, FillNameQuery.fillValue( sql, admin.get( "topaid" ) ) );
		return intermediate;
	}
	
	private String getUploadDirectory( Map< String, Object > intermediate, Map< String, Object > admin ){
		
		if( intermediate == null || intermediate.isEmpty( ) ){
			return null;
		}
		
		Integer groupid = ( Integer ) admin.get( "groupid" );
		
		if( groupid != 2 ){
			return null;
		}
		return Constants.UPLOAD_DIRECTORY + intermediate.get( "id" ) + "/";
		
	}	
	
	private void appendContent( String content, StringBuffer buffer ){
		buffer.append( content );
		buffer.append(  "\r\n" );
	}
	
	private static final long serialVersionUID = 1L;
	
	private String getRealPath( String path ){
		if (path == null) {
		    path = "/";
		}
		return ServletActionContext.getServletContext().getRealPath( path );
		
	}
	
	private void makeDirs( String file ){
		File f = new File( file );
		if(! f.exists( ) ){
			f.mkdirs( );
		}
	}
	
	private String basic_softname;
	private String basic_homepage;
	private String basic_logo;
	
	private String topbutton_rightfirst;
	private String topbutton_rightdisplay;
	private String topbutton_rightsecond;
	private String topbutton_rightsecond_url;
	private String topbutton_rightsecond_blank;
	private String topbutton_rightthird;
	private String topbutton_rightthird_url;
	private String topbutton_rightthird_blank;
	
	private String leftbutton_first;
	private String leftbutton_second;
	private String leftbutton_third;
	private String leftbutton_third_url;
	private String leftbutton_four;
	private String leftbutton_four_url;
	private String leftbutton_five;
	private String leftbutton_five_url;
	private String leftbutton_six;
	private String leftbutton_six_url;
	
	
	
    private File  Filedata;
    private String Filename;
   
	public String getFilename( ) {
		return Filename;
	}

	public void setFilename( String filename ) {
		Filename = filename;
	}

	public File getFiledata( ) {
		return Filedata;
	}

	public void setFiledata( File filedata ) {
		Filedata = filedata;
	}

	public String getBasic_softname( ) {
		return basic_softname;
	}

	public void setBasic_softname( String basicSoftname ) {
		if( StringUtils.isNotBlank( basicSoftname )){
			basicSoftname = decode( basicSoftname );
		}
		basic_softname = basicSoftname;
	}

	public String getBasic_homepage( ) {
		return basic_homepage;
	}

	public void setBasic_homepage( String basicHomepage ) {
		if( StringUtils.isNotBlank( basicHomepage )){
			basicHomepage = decode( basicHomepage );
		}
		basic_homepage = basicHomepage;
	}

	public String getBasic_logo( ) {
		return basic_logo;
	}

	public void setBasic_logo( String basicLogo ) {
		if( StringUtils.isNotBlank( basicLogo )){
			basicLogo = decode( basicLogo );
		}
		basic_logo = basicLogo;
	}

	public String getTopbutton_rightfirst( ) {
		return topbutton_rightfirst;
	}

	public void setTopbutton_rightfirst( String topbuttonRightfirst ) {
		if( StringUtils.isNotBlank( topbuttonRightfirst )){
			topbuttonRightfirst= decode( topbuttonRightfirst );
		}
		topbutton_rightfirst = topbuttonRightfirst;
	}

	public String getTopbutton_rightdisplay( ) {
		return topbutton_rightdisplay;
	}

	public void setTopbutton_rightdisplay( String topbuttonRightdisplay ) {
		if( "1".equals( topbuttonRightdisplay )){
			topbuttonRightdisplay = "真";
		}else{
			topbuttonRightdisplay = "假";
		}
		topbutton_rightdisplay = topbuttonRightdisplay;
	}

	public String getTopbutton_rightsecond( ) {
		return topbutton_rightsecond;
	}

	public void setTopbutton_rightsecond( String topbuttonRightsecond ) {
		if( StringUtils.isNotBlank( topbuttonRightsecond )){
			topbuttonRightsecond = decode( topbuttonRightsecond );
		}
		topbutton_rightsecond = topbuttonRightsecond;
	}

	public String getTopbutton_rightsecond_url( ) {
		return topbutton_rightsecond_url;
	}

	public void setTopbutton_rightsecond_url( String topbuttonRightsecondUrl ) {
		if( StringUtils.isNotBlank( topbuttonRightsecondUrl )){
			topbuttonRightsecondUrl = decode( topbuttonRightsecondUrl );
		}
		topbutton_rightsecond_url = topbuttonRightsecondUrl;
	}

	public String getTopbutton_rightsecond_blank( ) {
		return topbutton_rightsecond_blank;
	}

	public void setTopbutton_rightsecond_blank( String topbuttonRightsecondBlank ) {
		if( "1".equals( topbuttonRightsecondBlank )){
			topbuttonRightsecondBlank = "是";
		}else{
			topbuttonRightsecondBlank = "否";
		}
		topbutton_rightsecond_blank = topbuttonRightsecondBlank;
	}

	public String getTopbutton_rightthird( ) {
		return topbutton_rightthird;
	}

	public void setTopbutton_rightthird( String topbuttonRightthird ) {
		if( StringUtils.isNotBlank( topbuttonRightthird )){
			topbuttonRightthird = decode( topbuttonRightthird );
		}
		topbutton_rightthird = topbuttonRightthird;
	}

	public String getTopbutton_rightthird_url( ) {
		return topbutton_rightthird_url;
	}

	public void setTopbutton_rightthird_url( String topbuttonRightthirdUrl ) {
		if( StringUtils.isNotBlank( topbuttonRightthirdUrl )){
			topbuttonRightthirdUrl= decode( topbuttonRightthirdUrl );
		}
		topbutton_rightthird_url = topbuttonRightthirdUrl;
	}

	public String getTopbutton_rightthird_blank( ) {
		return topbutton_rightthird_blank;
	}

	public void setTopbutton_rightthird_blank( String topbuttonRightthirdBlank ) {
		if( "1".equals( topbuttonRightthirdBlank )){
			topbuttonRightthirdBlank = "是";
		}else{
			topbuttonRightthirdBlank = "否";
		}
		topbutton_rightthird_blank = topbuttonRightthirdBlank;
	}

	public String getLeftbutton_first( ) {
		return leftbutton_first;
	}

	public void setLeftbutton_first( String leftbuttonFirst ) {
		if( StringUtils.isNotBlank( leftbuttonFirst )){
			leftbuttonFirst = decode( leftbuttonFirst );
		}
		leftbutton_first = leftbuttonFirst;
	}

	public String getLeftbutton_second( ) {
		return leftbutton_second;
	}

	public void setLeftbutton_second( String leftbuttonSecond ) {
		if( StringUtils.isNotBlank( leftbuttonSecond )){
			leftbuttonSecond = decode( leftbuttonSecond );
		}
		leftbutton_second = leftbuttonSecond;
	}

	public String getLeftbutton_third( ) {
		return leftbutton_third;
	}

	public void setLeftbutton_third( String leftbuttonThird ) {
		if( StringUtils.isNotBlank( leftbuttonThird )){
			leftbuttonThird = decode( leftbuttonThird );
		}
		leftbutton_third = leftbuttonThird;
	}

	public String getLeftbutton_third_url( ) {
		return leftbutton_third_url;
	}

	public void setLeftbutton_third_url( String leftbuttonThirdUrl ) {
		if( StringUtils.isNotBlank( leftbuttonThirdUrl )){
			leftbuttonThirdUrl = decode( leftbuttonThirdUrl );
		}
		leftbutton_third_url = leftbuttonThirdUrl;
	}

	public String getLeftbutton_four( ) {
		return leftbutton_four;
	}

	public void setLeftbutton_four( String leftbuttonFour ) {
		if( StringUtils.isNotBlank( leftbuttonFour )){
			leftbuttonFour = decode( leftbuttonFour );
		}
		leftbutton_four = leftbuttonFour;
	}

	public String getLeftbutton_four_url( ) {
		return leftbutton_four_url;
	}

	public void setLeftbutton_four_url( String leftbuttonFourUrl ) {
		if( StringUtils.isNotBlank( leftbuttonFourUrl )){
			leftbuttonFourUrl = decode( leftbuttonFourUrl );
		}
		leftbutton_four_url = leftbuttonFourUrl;
	}

	public String getLeftbutton_five( ) {
		return leftbutton_five;
	}

	public void setLeftbutton_five( String leftbuttonFive ) {
		if( StringUtils.isNotBlank( leftbuttonFive )){
			leftbuttonFive = decode( leftbuttonFive );
		}
		leftbutton_five = leftbuttonFive;
	}

	public String getLeftbutton_five_url( ) {
		return leftbutton_five_url;
	}

	public void setLeftbutton_five_url( String leftbuttonFiveUrl ) {
		if( StringUtils.isNotBlank( leftbuttonFiveUrl )){
			leftbuttonFiveUrl = decode( leftbuttonFiveUrl );
		}
		leftbutton_five_url = leftbuttonFiveUrl;
	}

	public String getLeftbutton_six( ) {
		return leftbutton_six;
	}

	public void setLeftbutton_six( String leftbuttonSix ) {
		if( StringUtils.isNotBlank( leftbuttonSix )){
			leftbuttonSix = decode( leftbuttonSix );
		}
		leftbutton_six = leftbuttonSix;
	}

	public String getLeftbutton_six_url( ) {
		return leftbutton_six_url;
	}

	public void setLeftbutton_six_url( String leftbuttonSixUrl ) {
		if( StringUtils.isNotBlank( leftbuttonSixUrl )){
			leftbuttonSixUrl= decode( leftbuttonSixUrl );
		}
		leftbutton_six_url = leftbuttonSixUrl;
	}
	
	
	
	
	
	
}
